package com.yuqing.sentimentapp.utils;

import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;

import com.linkface.baselibrary.utils.FileUtils;
import com.linkface.baselibrary.utils.LogUtil;
import com.yuqing.sentimentapp.BuildConfig;
import com.yuqing.sentimentapp.MainActivity;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.linkface.baselibrary.http.RetrofitClient;
import com.linkface.baselibrary.utils.AppManager;
import com.linkface.baselibrary.utils.SharedPrefUtils;
import com.yuqing.sentimentapp.QYApplication;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.api.ApiService;
import com.yuqing.sentimentapp.interfaces.ScheduleListener;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.update.UpdateInfoBean;
import com.yuqing.sentimentapp.update.UpdateService;
import com.yuqing.sentimentapp.utils.net.NetWorkUtil;
import com.yuqing.sentimentapp.widget.dialog.UpdateAppDialog;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ShenHe on 20119/4/17.
 */
@SuppressWarnings("all")
public class UpdateAppManager {
    //是否有更新
    private static boolean IS_UPDATE = false;
    //是否必须更新
    private static boolean IS_MUST = false;
    //是否正在下载
    private static boolean IS_DOWNLOAD = false;
    //APK的MD5值 用于校验下载的文件是否完整
    private static String M_MD5 = "";
    //是否使用MD5校验apk文件
    private static boolean M_USE_MD5_CHECK = false;
    //DownloadManager在后台下载id
    public static final String DMID = "DownloadManagerID";
    //更新下载路径
    public static String DOWNLOAD_URL;

    private static String MESSAGE;

    public static String FILEPATH;
    public static String NAME;
    //有更新
    private static final String HAVE = "Y";
    //无更新
    private static final String NOT = "N";

    private DownloadManager downloadManager;
    public long id;
//    private static String ApkPath;

    private static UpdateAppManager INSTANCE = new UpdateAppManager();

    public static final int ISDOWNLOAD = 0;
    public static final int DOWNLOADING = 1;
    public static final int NOTDOWNLOAD = 2;

    public static UpdateAppManager getUpdateAppManager() {
        return INSTANCE;
    }

    /**
     * 初始化
     */
    public void init() {
        IS_UPDATE = false;
        IS_MUST = false;
        DOWNLOAD_URL = "";
        MESSAGE = "";
        M_MD5 = "";
        NAME = "";
        M_USE_MD5_CHECK = false;
    }

    /**
     * 网络检查是否有更新
     *
     * @param listener 检查进程接口回掉
     */
    public void onlineCheckAppUpdate(final ScheduleListener listener) {
        if (!NetWorkUtil.isConnected(null)) {
            return;
        }
        if (listener != null) {
            listener.start();
        }

        Observable<UpdateInfoBean> observable = RetrofitClient.getInstance(QYApplication.getAppContext(), null, ModuleManager.getInstance().getHeaderMap()).create(ApiService.class).getUpdateInfo(BuildConfig.VERSION_CODE);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UpdateInfoBean>() {
                    @Override
                    protected void hideDialog() {
                    }

                    @Override
                    protected void showDialog() {
                    }

                    @Override
                    protected void onSuccess(UpdateInfoBean updateInfoBean) {
                        UpdateInfoBean.DataBean dataBean = updateInfoBean.getData();
                        if (HAVE.equals(dataBean.getUpdate())) {
                            IS_UPDATE = true;
                            DOWNLOAD_URL = dataBean.getApkPos();
                            MESSAGE = dataBean.getRemark();
                            M_MD5 = "";
                            NAME = dataBean.getApkName();
                            M_USE_MD5_CHECK = false;
                        } else {
                            IS_UPDATE = false;
                        }
                        IS_MUST = HAVE.equals(dataBean.getForce());
                        if (listener != null) {
                            listener.end(true);
                        }
                    }

                    @Override
                    protected void onFailure(String message) {
                        if (listener != null) {
                            listener.end(true);
                        }

                    }
                });
    }

    /**
     * 弹更新对话框
     *
     * @param mContext  上下文
     * @param showToast 是否toast提示用户
     */
    public void showDialog(Activity mContext, boolean showToast) {
        showDialog(mContext, false, showToast);
    }

    /**
     * 更新有WIFI静默下载，下载完成后下次启动客户端时弹更新窗提示
     * 更新无WIFI，强制更新有或没有WIFI都直接弹下载窗提示
     *
     * @param backDownLoad 是否允许后台先默认下载
     * @param showToast    Toast通知用户下载状态
     * @param mContext     mContext
     */
    public void showDialog(final Activity mContext, boolean backDownLoad, boolean showToast) {
        //设置文件存放目录
        String url = DOWNLOAD_URL;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            FILEPATH = Environment.getExternalStoragePublicDirectory(Environment
                    .DIRECTORY_DOWNLOADS).toString() + "/" + NAME;
        }
        //apk下载好的话弹安装对话框
        if (!IS_MUST && checkFile(mContext, showToast, true)) {
            return;
        }
        //Wifi下直接下载
        if (NetWorkUtil.isConnected(mContext) && (NetWorkUtil.getNetworkType(mContext) ==
                NetWorkUtil.NetType.NETWORK_WIFI) && FILEPATH != null && !FILEPATH.isEmpty() &&
                !IS_MUST && backDownLoad) {
            downloadManager(mContext, true);
        } else {
            //强制更新或无WIFI弹下载对话框
            initDownLoadDialog(mContext);
        }
    }

    /**
     * 初始化直接安装dialog
     *
     * @param mContext    上下文
     */
    public void initUpdateDialog(final Activity mContext) {
        final UpdateAppDialog updateAppDialog = new UpdateAppDialog(mContext);
        updateAppDialog.setMessage(MESSAGE);
        updateAppDialog.setCancleButtonListener(new UpdateAppDialog.ButtonListener() {
            @Override
            public void buttonOkClick(Dialog dialog) {
                updateAppDialog.cancel();
            }
        });
        updateAppDialog.setOkButtonListener(new UpdateAppDialog.ButtonListener() {
            @Override
            public void buttonOkClick(Dialog dialog) {
                //隐式跳转打开apk安装包
                File file = new File(FILEPATH);
                if (file.exists()) {
                    new InstallUtil(mContext, FILEPATH).install();
                } else {
                    updateAppDialog.cancel();
                }
            }
        });
        updateAppDialog.show();
    }

    /**
     * 初始化直接下载dialog
     *
     * @param mContext    上下文
     */
    public void initDownLoadDialog(final Context mContext) {
        UpdateAppDialog updateAppDialog = new UpdateAppDialog(mContext);
        updateAppDialog.setMessage(MESSAGE);
        updateAppDialog.setCancleButtonListener(new UpdateAppDialog.ButtonListener() {
            @Override
            public void buttonOkClick(Dialog dialog) {
                updateAppDialog.cancel();
//                downloadFile(mContext);
            }
        });
        if (IS_MUST) {
            updateAppDialog.setCancelable(false);
            updateAppDialog.setCancleVisiable(View.GONE);
            updateAppDialog.setOkButtonListener(new UpdateAppDialog.ButtonListener() {
                @Override
                public void buttonOkClick(Dialog dialog) {
                    ToastUtil.showShort("正在后台下载");
                    downloadManager(mContext, true);
                }
            });
        } else {
            updateAppDialog.setCancleVisiable(View.VISIBLE);
            updateAppDialog.setOkButtonListener(new UpdateAppDialog.ButtonListener() {
                @Override
                public void buttonOkClick(Dialog dialog) {
                    //非WIFI下不跟新，先创建一个WIFI下自动后台载任务
                    if (NetWorkUtil.isConnected(mContext) && (NetWorkUtil.getNetworkType
                            (mContext) == NetWorkUtil.NetType.NETWORK_WIFI) && FILEPATH != null
                            && !FILEPATH.isEmpty()) {
                        File file = new File(FILEPATH);
                        if (!file.exists()) {
                            /*DownloadManager.Request request = new DownloadManager.Request(Uri
                            .parse(downLoadUrl));
                            request.setDestinationInExternalFilesDir(BaseApp.app, Environment
                            .DIRECTORY_DOWNLOADS, name);
                            request.setNotificationVisibility(DownloadManager.Request
                            .VISIBILITY_HIDDEN);
                            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
                            downloadManager = (DownloadManager) mContext.getSystemService(Context
                            .DOWNLOAD_SERVICE);
                            id = downloadManager.enqueue(request);
                            //记录后台默认下载id
                            SRPreferences.getInstance().setLong(DMID, id);
                            isDownLoad = true;*/
                            downloadManager(mContext, true);
                        }
                    }
                }
            });
        }
        updateAppDialog.show();
    }

    /**
     * 判断apk是否已存在，并根据文件状态判断是否去安装
     *
     * @param mContext    上下文对象
     * @param showToast   是否提示用户
     * @param initUpdate  是弹直接安装对话框，否直接跳转安装
     * @return
     */
    public boolean checkFile(Activity mContext, boolean showToast, boolean initUpdate) {
        boolean an = false;
        switch (isFileExists(mContext, showToast)) {
            case ISDOWNLOAD:
                if (initUpdate) {
                    initUpdateDialog(mContext);
                } else {
                    Intent activityIntent = new Intent(Intent.ACTION_VIEW);
                    activityIntent.setDataAndType(Uri.parse("file://" + FILEPATH),
                            "application/vnd.android.package-archive");
                    activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(activityIntent);
                    AppManager.getAppManager().finishAllActivity();
                }
                an = true;
                break;
            case DOWNLOADING:
                an = true;
                break;
            default:
                an = false;
                break;
        }
        return an;
    }

    /**
     * 判断文件状态，文件下载完进行MD5检验，不合格为未下载
     *
     * @param mContext  上下文
     * @param showToast 是否提示用户
     * @return 返回文件是下载完，正在下载，还是未下载
     */
    public int isFileExists(Context mContext, boolean showToast) {
        //apk下载好的话弹安装对话框
        if (FILEPATH != null && !FILEPATH.isEmpty()) {
            File file = new File(FILEPATH);
            if (file.exists()) {
                //判断后台是否有下载
                if (SharedPrefUtils.getLong(UpdateAppManager.DMID, (long) -1) == -1) {
                    if (IS_DOWNLOAD) {
                        if (showToast) {
                            ToastUtil.showShort(mContext.getResources()
                                    .getString(R.string.isDownLoad));
                        }
                        return DOWNLOADING;
                    }
                    if (M_USE_MD5_CHECK && !TextUtils.isEmpty(M_MD5)) {//需要进行文件md5校验
//                        String downloadFileMd5 = MD5Helper.getMd5(file).toLowerCase();
//                        //对下载的文件进行md5校验
//                        if (!TextUtils.isEmpty(M_MD5) && !TextUtils.isEmpty(downloadFileMd5) &&
//                                M_MD5.equals(downloadFileMd5)) {
//                            //initUpdateDialog(mContext);
//                            return ISDOWNLOAD;
//                        } else {//md5 校验不成功 则删除文件
//                            ToastUtil.showShort("新版本文件下载失败,请尝试重新下载");
//                            try {
//                                file.delete();
//                                return NOTDOWNLOAD;
//                            } catch (Exception e) {
//                            }
//                        }
                    } else {//不需要进行文件MD5校验
                        //initUpdateDialog(mContext);
                        return ISDOWNLOAD;
                    }
                } else {
                    //判断后台下载是否完成
                    if (isDownloadManagerAvailable(mContext)) {
                        try {
                            DownloadManager.Query query = new DownloadManager.Query();
                            query.setFilterById(SharedPrefUtils.getLong
                                    (UpdateAppManager.DMID, (long) -1));
                            downloadManager = (DownloadManager) mContext.getSystemService(Context
                                    .DOWNLOAD_SERVICE);
                            Cursor cursor = downloadManager.query(query);
                            cursor.moveToFirst();
                            if (cursor.getInt(cursor.getColumnIndex(DownloadManager
                                    .COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                                if (M_USE_MD5_CHECK && !TextUtils.isEmpty(M_MD5)) {//需要进行文件md5校验
//                                    String downloadFileMd5 = MD5Helper.getMd5(file).toLowerCase();
//                                    //对下载的文件进行md5校验
//                                    if (!TextUtils.isEmpty(M_MD5) && !TextUtils.isEmpty
//                                            (downloadFileMd5) && M_MD5.equals(downloadFileMd5)) {
//                                        //initUpdateDialog(mContext);
//                                        //清除后台默认下载id
//                                        SRPreferences.getInstance().setLong(UpdateAppManager
//                                                .DMID, (long) -1);
//                                        return ISDOWNLOAD;
//                                    } else {//md5 校验不成功 则删除文件
//                                        GlobalToast.show("新版本文件下载失败,请尝试重新下载");
//                                        try {
//                                            file.delete();
//                                            return NOTDOWNLOAD;
//                                        } catch (Exception e) {
//                                        }
//                                    }
                                } else {
                                    //initUpdateDialog(mContext);
                                    //清除后台默认下载id
                                    SharedPrefUtils.saveLong(UpdateAppManager.DMID,
                                            (long) -1);
                                    return ISDOWNLOAD;
                                }
                            } else {
                                if (showToast) {
                                    ToastUtil.showShort(mContext.getResources()
                                            .getString(R.string.isDownLoad));
                                }
                                return DOWNLOADING;
                            }
                        } catch (Exception e) {
//                            if (M_USE_MD5_CHECK && !TextUtils.isEmpty(M_MD5)) {//需要进行文件md5校验
//                                String downloadFileMd5 = MD5Helper.getMd5(file).toLowerCase();
//                                //对下载的文件进行md5校验
//                                if (!TextUtils.isEmpty(M_MD5) && !TextUtils.isEmpty
//                                        (downloadFileMd5) && M_MD5.equals(downloadFileMd5)) {
//                                    SRPreferences.getInstance().setLong(UpdateAppManager.DMID,
//                                            (long) -1);
//                                    return ISDOWNLOAD;
//                                }
//                            }
//                            if (file.exists()) {
//                                file.delete();
//                            }
                            SharedPrefUtils.saveLong(UpdateAppManager.DMID, (long) -1);
                            return NOTDOWNLOAD;
                        }
                    } else {
                        //清除后台默认下载id
                        SharedPrefUtils.saveLong(UpdateAppManager.DMID, (long) -1);
                    }
                }
            }
        }
        return NOTDOWNLOAD;
    }

    /**
     * 判断DownloadManager是否有权限
     *
     * @param mContext 上下文
     * @return 是否有
     */
    public boolean isDownloadManagerAvailable(Context mContext) {
        try {
            if (mContext.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == mContext
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED_USER
                    || mContext.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == mContext
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED
                    || mContext.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == mContext
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {

                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 开启下载，没DownloadManager权限就启动一个服务下载
     *
     * @param mContext 上下文
     * @param isNotify 是否在通知栏提示用户下载进程
     */
    public void downloadManager(Context mContext, boolean isNotify) {
        Intent intent = new Intent(mContext, UpdateService.class);
        intent.putExtra("apkUrl", DOWNLOAD_URL);
        intent.putExtra("name", NAME);
        intent.putExtra("isNotify", isNotify);
        mContext.startService(intent);
        mContext.bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                UpdateService.MyBinder myBinder = (UpdateService.MyBinder)service;
                UpdateService updateService = myBinder.getService();
                updateService.setMainActivity((Activity) mContext);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        }, Context.BIND_AUTO_CREATE);
    }

    /**
     * 请求网络下载Apk
     * @param isBookStore 是否是在书架页调用的弹框
     * @param mContext 上下文
     */
    public void downloadFile(Activity mContext) {
        if (checkFile(mContext, true, false)) {
            return;
        }

        downloadManager(mContext, true);
    }

    public static boolean isUpdate() {
        return IS_UPDATE && DOWNLOAD_URL != null && NAME != null && !NAME.isEmpty() && NAME
                .endsWith(".apk");
    }

    public static boolean isMust() {
        return IS_MUST;
    }

    public static String getMd5() {
        return M_MD5;
    }

    /**
     * 是否需要MD5校验
     * @return ismUseMd5Check
     */
    public static boolean ismUseMd5Check() {
        return M_USE_MD5_CHECK;
    }

    public static void setIsDownLoad(boolean isDown) {
        IS_DOWNLOAD = isDown;
    }

    /**
     * isDownLoad
     * @return isDownLoad
     */
    public static boolean isDownLoad() {
        return IS_DOWNLOAD;
    }

    /**
     * 清除id
     */
    public void clearId() {
        id = -1;
    }

}
